const env = require('./config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
const base64 = require('./base64.js'); //Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

let upload_after_list = [];
let upload_picture_list = [];

const getPolicyBase64 = () => {
    let date = new Date();
    date.setHours(date.getHours() + env.timeout);
    let srcT = date.toISOString();
    const policyText = {
        "expiration": srcT,
        "conditions": [
            ["content-length-range", 0, 5 * 1024 * 1024] //上传容量最大为5M
        ]
    };
    const policyBase64 = base64.encode(JSON.stringify(policyText));
    return policyBase64;
}

const getSignature = (policyBase64) => {
    const accesskey = env.AccessKeySecret;
    const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
        asBytes: true
    });
    const signature = Crypto.util.bytesToBase64(bytes);
    return signature;
}

// 选择图片(通用)
const chooseImage = (options) => {
    let config = {
        count: options.count || 1,
        tips: false,
        notli: false,
        sourceType: options.sourceType || '',
        sizeType: true
    };
    return new Promise((resolve, reject) => {
		uni.chooseImage({
		    count: config.notli ? config.count = 9 : upload_after_list.length == 0 ? config.count : config.count -
		        upload_after_list.length,
		    sizeType: config.sizeType == "" || config.sizeType == undefined || config.sizeType == true ? ['compressed'] : [
		        'original'
		    ],
		    sourceType: config.sourceType == "" || config.sourceType == undefined ? ['album', 'camera'] : config.sourceType ==
		        'camera' ? ['camera'] : config.sourceType == 'album' ? ['album'] : ['album', 'camera'],
		    success: (res) => {
				let imagesArr = [];
		        for (let i = 0, len = res.tempFiles.length; i < len; i++) {
		            res.tempFiles[i]['upload_percent'] = 0;
		            res.tempFiles[i]['path_server'] = '';
		            imagesArr.push(res.tempFiles[i]);
		            imagesArr.length > config.count ? imagesArr = imagesArr.slice(0, config.count) : '';
		        }
		        resolve({code: 1, data: imagesArr});
		    }
		});
	});
}

// 过滤超出的图片以及上传(通用)
const fImage = (res, config) => {
    !config.notli && config.count == upload_picture_list.length ? uploadsImage(config) : '';
    config.notli && config.count == 9 ? uploadsImage(config) : '';
    upload_after_list = upload_after_list.concat(res.tempFilePaths).slice(0, config.count);
    upload_picture_list = upload_picture_list.slice(0, config.count);
}

// 上传图片(通用)
const uploadImage = async (imagesArr) => {
	let resImage = [];
    for (let j = 0, len = imagesArr.length; j < len; j++) {
		let imageItem = imagesArr[j];
        if (imageItem['upload_percent'] == 0) {
           let res = await upload_file_server(imageItem);
		   res && resImage.push(res);
        }
    }
	if(resImage.length > 0) {
		return Promise.resolve({code: 1, data: resImage});
	} else {
		return Promise.resolve({code: 0, data: []});
	}
}

// 上传文件
const upload_file_server = async (imageItem) => {
	
	let aliConfig = {
		aliyunFilePath: env.OSSDirectory,
        aliyunFileKey: new Date().getTime() + Math.floor(Math.random() * 150) + '.png',
        aliyunServerURL: env.uploadImageUrl,
        accessid: env.OSSAccessKeyId,
        url: env.uploadImageUrl || "",
        oos: false
    }
    const aliyunFileKey = aliConfig.aliyunFilePath + '/' + aliConfig.aliyunFileKey || "";
    const aliyunServerURL = aliConfig.aliyunServerURL || "";
    const accessid = aliConfig.accessid || "";
    const policyBase64 = getPolicyBase64();
    const signature = getSignature(policyBase64);
	
	uni.showLoading({
		title: `上传中...`
	});
	
	return new Promise((resolve, reject) => {
		const upload_task = uni.uploadFile({
			url: aliConfig.url,
			filePath: imageItem['path'],
			name: 'file',
			formData: {
				'key': aliyunFileKey,
				'policy': policyBase64,
				'OSSAccessKeyId': accessid,
				'signature': signature,
				'success_action_status': '200',
			},
			success(res) {
				if (res.statusCode == 200) {
					imageItem['name_server'] = aliConfig.aliyunFileKey;
					imageItem['path_server'] = aliyunServerURL + aliyunFileKey;
					uni.hideLoading();
					resolve(imageItem);
				} else {
					// uni.showLoading({
					// 	title: JSON.stringify(res),
					// });
					uni.showLoading({
						title: `上传失败!`
					});
					setTimeout(() => {
						uni.hideLoading();
					}, 2000);
					resolve(false);
				}
			},
			fail(err) {
				// uni.showLoading({
				// 	title: JSON.stringify(err),
				// });
				uni.showLoading({
					title: `上传失败!`
				});
				setTimeout(() => {
					uni.hideLoading();
				}, 2000);
				resolve(false);
			}
		});		
	});
}

// 上传前预览图片(通用)
const pImage = (e, _this) => {
    uni.previewImage({
        current: this.upload_after_list[e.currentTarget.dataset.index],
        urls: this.upload_after_list
    })
}

// 上传后预览(通用)
const puploadsImage = async (e, _this) => {
    let prevImgArr = [];
    for (let i = 0, len = _this.upload_picture_list.length; i < len; i++) {
        prevImgArr.push(_this.upload_picture_list[i].path_server);
    }
    uni.previewImage({
        current: e.currentTarget.dataset.src,
        urls: prevImgArr
    });
}

// 模块导出
module.exports = {
	uploadImage,
	chooseImage,
}